
import DropBox from "./DropBox";
import Bullet from "./Bullet";
/**
 * 游戏控制脚本。定义了几个dropBox，bullet，createBoxInterval等变量，能够在IDE显示及设置该变量
 * 更多类型定义，请参考官方文档
 */
export default class GameControl extends Laya.Script {
    /** @prop {name:box1,tips:"掉落容器预制体对象1",type:Prefab}*/
    box1: Laya.Prefab;
    private box_1: Laya.Sprite;
    /** @prop {name:box2,tips:"掉落容器预制体对象2",type:Prefab}*/
    box2: Laya.Prefab;
    private box_2: Laya.Sprite;
    /** @prop {name:box3,tips:"掉落容器预制体对象3",type:Prefab}*/
    box3: Laya.Prefab;
    private box_3: Laya.Sprite;
    /** @prop {name:createBoxInterval,tips:"间隔多少毫秒创建一个下跌的容器",type:int,default:1000}*/
    createBoxInterval: number = 1000;
    /**开始时间*/
    private _time: number = 0;
    /**是否已经开始游戏 */
    private _started: boolean = false;
    /**子弹和盒子所在的容器对象 */
    private _gameBox: Laya.Sprite;

    /**盒子等级 */
	private _level: number = 1;

    /* 构造函数 */
    constructor() { super(); }

    onEnable(): void {
        this._gameBox = this.owner.getChildByName("gameBox") as Laya.Sprite;
        this.createBox();
    }

    onUpdate(): void {

    }

    createBox(): void {
        /* 盒子等级：1/2/3 随机掉落 */
        this._level = Math.round(Math.random() * 2) + 1;

         //使用对象池创建盒子
        switch(this._level){
            case 1 :
            this.box_1 = Laya.Pool.getItemByCreateFun("box1", this.box1.create, this.box1);
            this.box_1.pos(Laya.stage.width/2, 0);
            this._gameBox.addChild(this.box_1);
            break;
            case 2 :
            this.box_2 = Laya.Pool.getItemByCreateFun("box2", this.box1.create, this.box1);
            this.box_2.pos(Laya.stage.width/2, 0);
            this._gameBox.addChild(this.box_2);
            break;
            case 3 :
            this.box_3 = Laya.Pool.getItemByCreateFun("box3", this.box1.create, this.box1);
            this.box_3.pos(Laya.stage.width/2, 0);
            this._gameBox.addChild(this.box_3);
            break;
        }
    }

    onStageClick(e: Laya.Event): void {
        //停止事件冒泡，提高性能，当然也可以不要
        e.stopPropagation();
        //舞台被点击后，使用对象池创建子弹
        let flyer: Laya.Sprite = Laya.Pool.getItemByCreateFun("bullet", this.bullet.create, this.bullet);
        flyer.pos(Laya.stage.mouseX, Laya.stage.mouseY);
        this._gameBox.addChild(flyer);
    }

    /**开始游戏，通过激活本脚本方式开始游戏*/
    startGame(): void {
        if (!this._started) {
            this._started = true;
            this.enabled = true;
        }
    }

    /**结束游戏，通过非激活本脚本停止游戏 */
    stopGame(): void {
        this._started = false;
        this.enabled = false;
        this.createBoxInterval = 1000;
        this._gameBox.removeChildren();
    }
}